<template>
  <div class="photo-upload-container">
    <div class="header">
      <h2>照片上传</h2>
      <p>为老人上传活动照片，家属可以在家属界面查看</p>
    </div>

    <div class="upload-section">
      <el-card class="upload-card">
        <template #header>
          <div class="card-header">
            <span>上传照片</span>
          </div>
        </template>

        <el-form :model="uploadForm" :rules="uploadRules" ref="uploadFormRef" label-width="100px">
          <el-form-item label="选择老人" prop="elderId">
            <el-select v-m+odel="uploadForm.elderId" placeholder="请选择老人" style="width: 100%">
              <el-option
                v-for="elder in elderList"
                :key="elder.elderId"
                :label="elder.name"
                :value="elder.elderId"
              >
                <span>{{ elder.name }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">
                  {{ elder.age }}岁
                </span>
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="照片描述" prop="description">
            <el-input
              v-model="uploadForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入照片描述，例如：老人参加书法活动、花园散步等"
              maxlength="200"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="上传照片" prop="photoFile">
            <el-upload
              class="upload-demo"
              ref="uploadRef"
              action="#"
              :auto-upload="false"
              :on-change="handleFileChange"
              :on-remove="handleFileRemove"
              :file-list="fileList"
              :limit="5"
              :on-exceed="handleExceed"
              accept="image/*"
              list-type="picture-card"
            >
              <el-icon><Plus /></el-icon>
              <div class="el-upload__text">
                点击上传照片<br/>
                <span style="color: #909399; font-size: 12px">支持 jpg、png 格式</span>
              </div>
            </el-upload>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleUpload" :loading="uploading">
              {{ uploading ? '上传中...' : '上传照片' }}
            </el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>

    <div class="photo-list-section">
      <el-card>
        <template #header>
          <div class="card-header">
            <span>已上传照片</span>
            <el-button type="primary" text @click="loadPhotoList">刷新</el-button>
          </div>
        </template>

        <div class="photo-grid" v-loading="loading">
          <div class="photo-item" v-for="photo in photoList" :key="photo.photoId">
            <div class="photo-card">
              <el-image
                :src="photo.photoUrl"
                :preview-src-list="[photo.photoUrl]"
                fit="cover"
                class="photo-image"
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon><Picture /></el-icon>
                  </div>
                </template>
              </el-image>
              <div class="photo-info">
                <div class="elder-name">{{ getElderName(photo.elderId) }}</div>
                <div class="photo-desc">{{ photo.description }}</div>
                <div class="upload-time">{{ formatTime(photo.createTime) }}</div>
              </div>
              <div class="photo-actions">
                <el-button type="danger" text @click="handleDelete(photo.photoId)">
                  删除
                </el-button>
              </div>
            </div>
          </div>

          <div class="empty-state" v-if="photoList.length === 0 && !loading">
            <el-empty description="暂无上传的照片" />
          </div>
        </div>

        <div class="pagination" v-if="photoList.length > 0">
          <el-pagination
            v-model:current-page="pagination.currentPage"
            v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Picture } from '@element-plus/icons-vue'
import { elderApi } from '@/api/elder'
import { uploadPhoto, getPhotos, deletePhoto } from '@/api/photo'

// 响应式数据
const uploadFormRef = ref()
const uploadRef = ref()
const uploading = ref(false)
const loading = ref(false)
const fileList = ref([])

const uploadForm = reactive({
  elderId: '',
  description: '',
  photoFile: null
})

const uploadRules = {
  elderId: [
    { required: true, message: '请选择老人', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入照片描述', trigger: 'blur' }
  ],
  photoFile: [
    { required: true, message: '请选择照片文件', trigger: 'change' }
  ]
}

const elderList = ref([])
const photoList = ref([])

const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 方法
const loadElderList = async () => {
  try {
    const response = await elderApi.getElders()
    if (response.data && response.data.success) {
      elderList.value = response.data.data || []
    }
  } catch (error) {
    ElMessage.error('获取老人列表失败')
    console.error('获取老人列表失败:', error)
  }
}

const loadPhotoList = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize
    }
    const response = await getPhotos(params)
    if (response.data && response.data.success) {
      photoList.value = response.data.data?.records || []
      pagination.total = response.data.data?.total || 0
    }
  } catch (error) {
    ElMessage.error('获取照片列表失败')
    console.error('获取照片列表失败:', error)
  } finally {
    loading.value = false
  }
}

const handleFileChange = (file) => {
  uploadForm.photoFile = file.raw
}

const handleFileRemove = () => {
  uploadForm.photoFile = null
}

const handleExceed = () => {
  ElMessage.warning('最多只能上传5张照片')
}

const handleUpload = async () => {
  if (!uploadFormRef.value) return

  try {
    await uploadFormRef.value.validate()
    
    if (!uploadForm.photoFile) {
      ElMessage.warning('请选择照片文件')
      return
    }

    uploading.value = true

    const formData = new FormData()
    formData.append('elderId', uploadForm.elderId)
    formData.append('description', uploadForm.description)
    formData.append('photoFile', uploadForm.photoFile)

    const response = await uploadPhoto(formData)
    if (response.data && response.data.success) {
      ElMessage.success('照片上传成功')
      resetForm()
      loadPhotoList()
    } else {
      ElMessage.error(response.data?.message || '照片上传失败')
    }
  } catch (error) {
    ElMessage.error('照片上传失败')
    console.error('照片上传失败:', error)
  } finally {
    uploading.value = false
  }
}

const resetForm = () => {
  uploadFormRef.value?.resetFields()
  uploadForm.photoFile = null
  fileList.value = []
  if (uploadRef.value) {
    uploadRef.value.clearFiles()
  }
}

const handleDelete = async (photoId) => {
  try {
    await ElMessageBox.confirm('确定要删除这张照片吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deletePhoto(photoId)
    if (response.data && response.data.success) {
      ElMessage.success('删除成功')
      loadPhotoList()
    } else {
      ElMessage.error(response.data?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error('删除失败:', error)
    }
  }
}

const getElderName = (elderId) => {
  const elder = elderList.value.find(item => item.elderId === elderId)
  return elder ? elder.name : '未知老人'
}

const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString('zh-CN')
}

const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.currentPage = 1
  loadPhotoList()
}

const handleCurrentChange = (newPage) => {
  pagination.currentPage = newPage
  loadPhotoList()
}

// 生命周期
onMounted(() => {
  loadElderList()
  loadPhotoList()
})
</script>

<style scoped>
.photo-upload-container {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  margin: 0;
  color: #303133;
}

.header p {
  margin: 5px 0 0 0;
  color: #909399;
  font-size: 14px;
}

.upload-section {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.upload-demo {
  width: 100%;
}

.photo-list-section {
  margin-top: 20px;
}

.photo-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.photo-item {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  transition: transform 0.3s, box-shadow 0.3s;
}

.photo-item:hover {
  transform: translateY(-4px);
  box-shadow: 0 4px 20px 0 rgba(0, 0, 0, 0.15);
}

.photo-card {
  background: white;
}

.photo-image {
  width: 100%;
  height: 200px;
  display: block;
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: #f5f7fa;
  color: #909399;
}

.photo-info {
  padding: 12px;
}

.elder-name {
  font-weight: bold;
  color: #303133;
  margin-bottom: 8px;
}

.photo-desc {
  color: #606266;
  font-size: 14px;
  margin-bottom: 8px;
  line-height: 1.4;
}

.upload-time {
  color: #909399;
  font-size: 12px;
}

.photo-actions {
  padding: 0 12px 12px;
  text-align: right;
}

.empty-state {
  grid-column: 1 / -1;
  text-align: center;
  padding: 40px 0;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

:deep(.el-upload--picture-card) {
  width: 100%;
  height: 120px;
}

:deep(.el-upload-list--picture-card .el-upload-list__item) {
  width: 148px;
  height: 148px;
}
</style>
